<template>
  <!-- components: ValidateForm -->
  <form class = "valiate-form-container">
    <slot name= "default"></slot>
    <div class = "submit-area text-center" v-on:click.prevent="submitForm">
      <slot name= "submit">
        <button
          class = "btn btn-primary"
          type = "submit"
        >提交</button>
      </slot>
    </div>
  </form>
</template>

<script lang = "ts">
import { defineComponent, onUnmounted } from 'vue'
// mitt 组件之间通讯
import mitt from 'mitt'

type ValidateFunc = () => boolean
// 定义一个 events 类型
type Events = {'form-item-created': ValidateFunc}
// 实例化 mitt 的时候，作为泛型传递进去
// 监听器
export const emitter = mitt<Events>()

// 对setup函数进行封装，返回options的对象
export default defineComponent({
  // 页面名称
  name: 'ValidateForm',
  // 发送事件
  emits: ['form-submit'],

  // 组合式api入口
  setup (props, context) {
    // 初始化数组
    let funcArr: ValidateFunc[] = []
    // 点击按钮
    const submitForm = () => {
      const result = funcArr.map(func => func()).every(result => result)
      // 发送事件
      context.emit('form-submit', result)
    }
    const callback = (func: ValidateFunc) => {
      funcArr.push(func)
    }
    // 开启接收器
    emitter.on('form-item-created', callback)
    // 生命周期函数
    onUnmounted(() => {
      // 关闭接收器
      emitter.off('form-item-created', callback)
      funcArr = []
    })
    return {
      submitForm
    }
  }
})
</script>

<style lang = "css" scoped>
.valiate-form-container{
  width: auto;
  max-width: 800px;
  margin: 0 auto;
}
</style>
